<!DOCTYPE html>
<html prefix="
og: http://ogp.me/ns#
article: http://ogp.me/ns/article#
" lang="zh_cn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>python function tools | vincent blog</title>
<link href="../../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../../rss.xml">
<link rel="canonical" href="https://wisonwang.github.io/posts/python-function-tools/">
<!--[if lt IE 9]><script src="/assets/js/html5.js"></script><![endif]--><meta name="author" content="vincent wang">
<meta property="og:site_name" content="vincent blog">
<meta property="og:title" content="python function tools">
<meta property="og:url" content="https://wisonwang.github.io/posts/python-function-tools/">
<meta property="og:description" content="In [3]:

    
import functools


    






In [4]:

    
import urllib

@functools.lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'http://">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2019-04-02T16:55:28+08:00">
</head>
<body>
    <section class="social"><ul>
<li><a href="../../index.html" title="Home"><i class="icon-home"></i></a></li>
            <li><a href="../../archive.html" title="文章存档"><i class="icon-archive"></i></a></li>
            <li><a href="../../categories/" title="标签"><i class="icon-tags"></i></a></li>
            <li><a href="../../pages/about" title="About"><i class="icon-about"></i></a></li>
            <li><a href="../../rss.xml" title="RSS 源"><i class="icon-rss"></i></a></li>
            <li><a href="https://twitter.com/wisonwang" title="My Twitter"><i class="icon-twitter"></i></a></li>
            <li><a href="https://github.com/wisonwang" title="My Github"><i class="icon-github"></i></a></li>

        </ul></section><section class="page-content"><div class="content" rel="main">
    <div class="post">
        <h1 class="p-name entry-title" itemprop="headline name">python function tools</h1>

        <div class="meta">
            <div class="authordate">
                <time class="timeago" datetime="2019-04-02T16:55:28+08:00">2019-04-02 16:55</time>
            
                      |  
        <a href="index.ipynb" id="sourcelink">源代码</a>

            </div>
            
        </div>
        <div class="body">
            <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<!-- TEASER_END -->
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
</pre></div>

    </div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [4]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span>

<span class="nd">@functools</span><span class="o">.</span><span class="n">lru_cache</span><span class="p">(</span><span class="n">maxsize</span><span class="o">=</span><span class="mi">32</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">get_pep</span><span class="p">(</span><span class="n">num</span><span class="p">):</span>
    <span class="s1">'Retrieve text of a Python Enhancement Proposal'</span>
    <span class="n">resource</span> <span class="o">=</span> <span class="s1">'http://www.python.org/dev/peps/pep-</span><span class="si">%04d</span><span class="s1">/'</span> <span class="o">%</span> <span class="n">num</span>
    <span class="k">try</span><span class="p">:</span>
        
        <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span> <span class="k">as</span> <span class="n">s</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="k">return</span> <span class="s1">'Not Found'</span>


<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">290</span><span class="p">,</span> <span class="mi">308</span><span class="p">,</span> <span class="mi">320</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">218</span><span class="p">,</span> <span class="mi">320</span><span class="p">,</span> <span class="mi">279</span><span class="p">,</span> <span class="mi">289</span><span class="p">,</span> <span class="mi">320</span><span class="p">,</span> <span class="mi">9991</span><span class="p">:</span>
    <span class="n">pep</span> <span class="o">=</span> <span class="n">get_pep</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">pep</span><span class="p">))</span>


<span class="n">get_pep</span><span class="o">.</span><span class="n">cache_info</span><span class="p">()</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt"></div>


<div class="output_subarea output_stream output_stdout output_text">
<pre>8 9
290 9
308 9
320 9
8 9
218 9
320 9
279 9
289 9
320 9
9991 9
</pre>
</div>
</div>

<div class="output_area">

    <div class="prompt output_prompt">Out[4]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [5]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># functools.partial固定函数可选参数，返回一个函数对象</span>
<span class="n">basetwo</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="n">base</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">basetwo</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">'Convert base 2 string to an int.'</span>

<span class="k">assert</span><span class="p">(</span><span class="n">basetwo</span><span class="p">(</span><span class="s1">'10010'</span><span class="p">)</span> <span class="o">==</span> <span class="nb">int</span><span class="p">(</span><span class="s1">'10010'</span><span class="p">,</span> <span class="n">base</span><span class="o">=</span><span class="mi">2</span><span class="p">))</span>
<span class="n">basetwo</span><span class="p">(</span><span class="s1">'10010'</span><span class="p">)</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt output_prompt">Out[5]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>18</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [6]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># functools.partialmethod 固定对象成员函数</span>
<span class="k">class</span> <span class="nc">Cell</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_alive</span> <span class="o">=</span> <span class="kc">False</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">alive</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_alive</span>

    <span class="k">def</span> <span class="nf">set_state</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_alive</span> <span class="o">=</span> <span class="nb">bool</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>

    <span class="n">set_alive</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partialmethod</span><span class="p">(</span><span class="n">set_state</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
    <span class="n">set_dead</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partialmethod</span><span class="p">(</span><span class="n">set_state</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>


<span class="n">c</span> <span class="o">=</span> <span class="n">Cell</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">alive</span>

<span class="n">c</span><span class="o">.</span><span class="n">set_alive</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">alive</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt output_prompt">Out[6]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>True</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">functools</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="p">[</span><span class="n">y</span><span class="p">],</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="p">[])</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt output_prompt">Out[7]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [8]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 函数分发封装</span>

<span class="nd">@functools</span><span class="o">.</span><span class="n">singledispatch</span>
<span class="k">def</span> <span class="nf">fun</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">verbose</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">"Let me just say,"</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">" "</span><span class="p">)</span>

    <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s2">"A"</span>


<span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="n">A</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s2">"B"</span>


<span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s2">"C"</span>


<span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s2">"C"</span>


<span class="nd">@fun</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">"print A obj: "</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span>


<span class="nd">@fun</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">B</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">"print B obj: "</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span>


<span class="nd">@fun</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">C</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">"print C obj: "</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span>



<span class="n">fun</span><span class="p">(</span><span class="n">A</span><span class="p">())</span>

<span class="n">fun</span><span class="p">(</span><span class="n">B</span><span class="p">())</span>

<span class="n">fun</span><span class="p">(</span><span class="n">C</span><span class="p">())</span>

<span class="n">fun</span><span class="p">(</span><span class="n">D</span><span class="p">())</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt"></div>


<div class="output_subarea output_stream output_stdout output_text">
<pre>print A obj:  &lt;__main__.A object at 0x10c944978&gt;
print B obj:  &lt;__main__.B object at 0x10c9449e8&gt;
print C obj:  &lt;__main__.C object at 0x10c944978&gt;
print B obj:  &lt;__main__.D object at 0x10c9449e8&gt;
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># functools.wraps 函数包装(等同partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated))</span>

<span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">'Calling decorated function'</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">wrapper</span>

<span class="nd">@my_decorator</span>
<span class="k">def</span> <span class="nf">example</span><span class="p">():</span>
    <span class="sd">"""Docstring"""</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">'Called example function'</span><span class="p">)</span>


<span class="n">example</span><span class="p">()</span>

<span class="nb">print</span><span class="p">(</span><span class="nb">dir</span><span class="p">(</span><span class="n">example</span><span class="p">))</span>

<span class="nb">print</span><span class="p">(</span><span class="n">functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="nb">int</span><span class="p">))</span>
</pre></div>

    </div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

    <div class="prompt"></div>


<div class="output_subarea output_stream output_stdout output_text">
<pre>Calling decorated function
Called example function
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__wrapped__']
functools.partial(&lt;function update_wrapper at 0x10aa9d8c8&gt;, wrapped=&lt;class 'int'&gt;, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span> 
</pre></div>

    </div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span> 
</pre></div>

    </div>
</div>
</div>

</div>
    </div>
  </div>

        </div>
                <ul class="pager hidden-print">
<li class="previous">
                <a href="../django-authoauth20/" rel="prev" title="django auth&amp;oauth2.0">前一篇</a>
            </li>
            <li class="next">
                <a href="../python-meta-class/" rel="next" title="python meta class">后一篇</a>
            </li>
        </ul>
<div id="disqus_thread"></div>
        <script>
        var disqus_shortname ="wisonwanghomepage",
            disqus_url="https://wisonwang.github.io/posts/python-function-tools/",
        disqus_title="python function tools",
        disqus_identifier="cache/posts/python-function-tools.html",
        disqus_config = function () {
            this.language = "zh_cn";
        };
        (function() {
            var dsq = document.createElement('script'); dsq.async = true;
            dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script><noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a>
</noscript>
    <a href="https://disqus.com" class="dsq-brlink" rel="nofollow">Comments powered by <span class="logo-disqus">Disqus</span></a>


    </div>
                     <footer id="footer"><p>Contents © 2020         <a href="mailto:fangfu2012@gmail.com">vincent wang</a> - Powered by         <a href="https://getnikola.com" rel="nofollow">Nikola</a>         </p>
            
        </footer>
</div>
    </section><script src="../../assets/js/all-nocdn.js" type="text/javascript"></script><script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script><script type="text/x-mathjax-config">
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$latex ','$'], ['\\(','\\)']]}});
    </script><script type="text/javascript">
            $(function(){
                $('.timeago').timeago();
            });
        </script>
</body>
</html>
